# encoding: utf-8
class TranslateService
  include Serviceable
  include StatusObject
  def initialize(text)
    @text = text
  end

  def call
    uri = URI($translate[:host])
    params = {
                keyfrom: $translate[:keyfrom],
                key: $translate[:key],
                type: "data",
                doctype: "json",
                version: "1.1",
                q: @text#.force_encoding("UTF-8")
              }
    uri.query = URI.encode_www_form(params)
    res = Net::HTTP.get_response(uri)
    result = JSON.parse(res.body)
    case result["errorCode"]
    when 0
      message = result["translation"].map(&->(i){i}).join("\n")
    when 20
      message = '要翻译的文本过长'
    when 30
      message = '无法进行有效的翻译'
    when 40
      message = '不支持的语言类型'
    when 60
      message = '无词典结果，仅在获取词典结果生效'
    end
    Status.new(success: true, message: message)
  rescue => e
    Status.new(success: true, message: e.message)
  end

  private
  def get

  end
end
